﻿using BW.Mes.WinForms.Process;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
using System.Windows.Forms;
using System.IO; // 添加这个引用来使用File类

namespace BW.Mes.WinForms.Production.Order
{
    public partial class OrderForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _workorderApiBaseUrl = "https://localhost:7223";
        private List<WorkOrderModel> _allWorkOrders; // 存储所有数据


        //构造函数
        public OrderForm()
        {
            InitializeComponent();

            //初始化httpClient
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri(_workorderApiBaseUrl);
            _httpClient.DefaultRequestHeaders.Accept.Clear();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            // 确保操作列配置正确
            ConfigureOperationColumn();

            // 绑定查询按钮点击事件
            simpleButton1.Click += simpleButton1_Click;

            //加载
            this.Load += gridControl1_Load;

            // 注册分页控件事件
            userControl11.ClickPageButtonEvent += UserControl1_ClickPageButtonEvent;
            userControl11.ChangedPageSizeEvent += UserControl1_ChangedPageSizeEvent;
            userControl11.JumpPageEvent += UserControl1_JumpPageEvent;


            //父子级
            this.IsMdiContainer = false;
        }

        /// <summary>
        /// 配置操作列和按钮编辑器
        /// </summary>
        private void ConfigureOperationColumn()
        {
            try
            {
                // 确保操作列的FieldName为空，避免数据绑定错误
                if (gridView1.Columns["operation"] != null)
                {
                    gridView1.Columns["operation"].FieldName = "";
                    gridView1.Columns["operation"].UnboundType = DevExpress.Data.UnboundColumnType.String;
                    gridView1.Columns["operation"].Width = 100;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"配置操作列时出错: {ex.Message}");
            }
        }

        //显示数据的方法（加载）
        private async void gridControl1_Load(object sender, EventArgs e)
        {
            await LoadWorkOrder();
            DisplayPagedData();
        }

        //添加工单的方法
        private void AddOrder_Click(object sender, EventArgs e)
        {
            var addOrder = new AddOrederForm();
            addOrder.ShowDialog(); // 这是弹出，不是跳转
        }


        //查询
        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            // 获取查询条件
            string orderCode = txt_code.Text.Trim();
            string orderCreateby = txt_createby.Text.Trim();
            DateTime? createTime = time_createda.EditValue as DateTime?;


            try
            {
                // 调用显示数据方法，传递条件
                await ShowData(orderCode, orderCreateby, createTime, 1); // 查询时回到第一页
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询异常：" + ex.Message);
            }

        }

        // 显示查询数据方法
        private async Task ShowData(string orderCode, string orderCreateby, DateTime? createTime, int page)
        {
            // 拼接API路径
            string queryParams = "";
            if (!string.IsNullOrEmpty(orderCode))
                queryParams += $"Code={orderCode}&";
            if (!string.IsNullOrEmpty(orderCreateby))
                queryParams += $"CreatedBy={orderCreateby}&";
            if (createTime.HasValue)
                queryParams += $"CreatedAt={createTime.Value:yyyy-MM-dd}&";
            if (!string.IsNullOrEmpty(queryParams))
                queryParams = "?" + queryParams.TrimEnd('&');

            // 获取数据后添加空值检查
            _allWorkOrders = await GetApiDataAsync<List<WorkOrderModel>>($"{_workorderApiBaseUrl}api/ProduceModel/GetWorkOrder{queryParams}");

            // 添加这段代码
            if (_allWorkOrders == null)
            {
                _allWorkOrders = new List<WorkOrderModel>(); // 初始化为空列表而非null
                MessageBox.Show("未获取到数据，请检查查询条件或网络连接", "提示");
            }
            // 更新分页控件
            userControl11.CurrentPage = page;
            userControl11.TotalRows = _allWorkOrders.Count;
            userControl11.TotalPages = (int)Math.Ceiling((double)_allWorkOrders.Count / userControl11.PageSize);
            userControl11.PageInfo.Text = $"第{userControl11.CurrentPage}/{userControl11.TotalPages}页";

            // 显示当前页数据
            DisplayPagedData();

        }


        //加载
        private async Task LoadWorkOrder()
        {
            try
            {
                _allWorkOrders = await GetApiDataAsync<List<WorkOrderModel>>("api/ProduceModel/GetWorkOrder");

                // 设置总记录数和总页数
                userControl11.TotalRows = _allWorkOrders.Count;
                userControl11.TotalPages = (int)Math.Ceiling((double)_allWorkOrders.Count / userControl11.PageSize);

                // 更新页码信息标签
                userControl11.PageInfo.Text = $"第{userControl11.CurrentPage}/{userControl11.TotalPages}页";

                // 为所有数据设置操作列的值
                foreach (var item in _allWorkOrders)
                {
                    item.operation = ""; // 设置为空字符串，使按钮显示
                }

                // 不在这里直接绑定数据，而是在DisplayPagedData方法中绑定
                DisplayPagedData();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}\n{ex.StackTrace}", "错误");
            }
        }
        // 显示分页后的数据
        private void DisplayPagedData()
        {
            if (_allWorkOrders == null || _allWorkOrders.Count == 0)
            {
                MessageBox.Show("没有数据", "提示");
                return;
            }

            int startIndex = (userControl11.CurrentPage - 1) * userControl11.PageSize;
            int count = Math.Min(userControl11.PageSize, _allWorkOrders.Count - startIndex);

            if (startIndex < 0 || count <= 0)
                return;

            // 获取当前页的数据
            var pagedData = _allWorkOrders.Skip(startIndex).Take(count).ToList();

            // 设置每个行项目的操作列值为空字符串（按钮用）
            foreach (var item in pagedData)
            {
                item.operation = "";  // 确保操作列有值但显示为按钮
            }

            // 绑定到GridControl
            gridControl1.DataSource = null;
            gridControl1.DataSource = pagedData;


            // 确保所有列的FieldName与数据模型属性名匹配
            foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridView1.Columns)
            {

                // 根据列名设置正确的FieldName
                switch (col.Name)
                {
                    case "Code": col.FieldName = "Code"; break;
                    case "ProductionType": col.FieldName = "ProductionType"; break;
                    case "CustomerName": col.FieldName = "CustomerName"; break;
                    case "Masterdata": col.FieldName = "Masterdata"; break;
                    case "ProcessName": col.FieldName = "ProcessName"; break;
                    case "State": col.FieldName = "State"; break;
                    case "Ids": col.FieldName = "IsSelected"; break;
                    case "Progress": col.FieldName = "Progress"; break;
                    case "ProductionCount": col.FieldName = "ProductionCount"; break;
                    case "BeginTime": col.FieldName = "BeginTime"; break;
                    case "EndTime": col.FieldName = "EndTime"; break;
                    case "Whether": col.FieldName = "Whether"; break;
                    case "Img": col.FieldName = "Img"; break;
                    case "ProductionDesc": col.FieldName = "ProductionDesc"; break;
                    case "Input": col.FieldName = "Input"; break;
                    case "Good": col.FieldName = "Good"; break;
                    case "Scrap": col.FieldName = "Scrap"; break;
                    case "Source": col.FieldName = "Source"; break;
                    case "ProductionNumber": col.FieldName = "ProductionNumber"; break;
                    case "CreatedBy": col.FieldName = "CreatedBy"; break;
                    case "CreatedAt": col.FieldName = "CreatedAt"; break;
                    case "operation": col.FieldName = ""; break; // 操作列使用空字段名
                }

                // 确保所有列都是可见的
                col.Visible = true;

                // 设置合适的列宽
                col.Width = 100;
            }

            // 刷新网格视图
            gridView1.BestFitColumns();

            // 添加安全检查，确保operation列存在
            try
            {
                if (gridView1.Columns["operation"] != null)
                {
                    // 设置操作列的宽度
                    gridView1.Columns["operation"].Width = 100; // 设置适当的宽度
                    // 设置操作列不自动调整大小
                    gridView1.OptionsView.ColumnAutoWidth = false;
                    gridView1.Columns["operation"].OptionsColumn.AllowSize = false;
                }
            }
            catch (Exception ex)
            {
                // 记录异常但不中断执行
                Console.WriteLine($"设置操作列属性时出错: {ex.Message}");
            }

            gridView1.RefreshData();
            gridView1.LayoutChanged();
        }

        // 页码按钮点击事件处理
        private async void UserControl1_ClickPageButtonEvent(int currentPage)
        {
            string orderCode = txt_code.Text.Trim();
            string orderCreateby = txt_createby.Text.Trim();

            DateTime? createTime = time_createda.EditValue as DateTime?;
            await ShowData(orderCode, orderCreateby, createTime, currentPage);
        }

        // 每页显示条数改变事件处理
        private async void UserControl1_ChangedPageSizeEvent()
        {
            string orderCode = txt_code.Text.Trim();
            string orderCreateby = txt_createby.Text.Trim();
            DateTime? createTime = time_createda.EditValue as DateTime?;
            await ShowData(orderCode, orderCreateby, createTime, 1);
            // 重新计算总页数
            userControl11.TotalPages = (int)Math.Ceiling((double)_allWorkOrders.Count / userControl11.PageSize);
            userControl11.PageInfo.Text = $"第{userControl11.CurrentPage}/{userControl11.TotalPages}页";
            DisplayPagedData();
        }

        // 跳转页面事件处理
        private async void UserControl1_JumpPageEvent(int jumpPage)
        {
            string orderCode = txt_code.Text.Trim();
            string orderCreateby = txt_createby.Text.Trim();
            DateTime? createTime = time_createda.EditValue as DateTime?;
            await ShowData(orderCode, orderCreateby, createTime, jumpPage);
            DisplayPagedData();
        }

        // 获取工单数据
        private async Task<T> GetApiDataAsync<T>(string endpoint)
        {
            try
            {
                // 显示请求URL，便于调试
                string requestUrl = $"{_workorderApiBaseUrl}/{endpoint}";
                Console.WriteLine($"请求URL: {requestUrl}");

                HttpResponseMessage response = await _httpClient.GetAsync(requestUrl);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                //MessageBox.Show($"API响应状态: {response.StatusCode}, 长度: {responseBody.Length}", "调试信息");

                // 检查响应内容是否为空
                if (string.IsNullOrWhiteSpace(responseBody))
                {
                    MessageBox.Show("API返回的数据为空", "警告");
                    return default;
                }

                try
                {
                    // 先解析为JObject以便提取内部数据
                    var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

                    // 假设数组数据在"PageDate"字段中
                    if (jsonObject["PageDate"] != null)
                    {
                        string dataJson = jsonObject["PageDate"].ToString();
                        Console.WriteLine($"提取的PageDate字段: {dataJson}");

                        var result = JsonConvert.DeserializeObject<T>(dataJson);
                        // 检查反序列化结果
                        if (result == null)
                        {
                            MessageBox.Show("PageDate字段反序列化结果为null", "警告");
                        }
                        else if (result is List<WorkOrderModel> workOrders)
                        {
                            //MessageBox.Show($"成功获取{workOrders.Count}条工单数据", "成功");
                        }
                        return result;
                    }
                    else
                    {
                        MessageBox.Show("响应中没有PageDate字段", "警告");
                    }

                    var directResult = JsonConvert.DeserializeObject<T>(responseBody);
                    // 检查直接反序列化结果
                    if (directResult == null)
                    {
                        MessageBox.Show("直接反序列化结果为null", "警告");
                    }
                    else if (directResult is List<WorkOrderModel> directWorkOrders)
                    {
                        MessageBox.Show($"直接反序列化成功获取{directWorkOrders.Count}条工单数据", "成功");
                    }
                    return directResult;
                }
                catch (JsonException jsonEx)
                {
                    MessageBox.Show($"JSON解析错误: {jsonEx.Message}\n响应内容: {responseBody.Substring(0, Math.Min(100, responseBody.Length))}...", "JSON错误");
                    return default;
                }
            }
            catch (HttpRequestException httpEx)
            {
                MessageBox.Show($"HTTP请求错误: {httpEx.Message}", "网络错误");
                return default;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取数据失败: {ex.Message}\n{ex.StackTrace}", "错误");
                return default;
            }
        }

        // 定义数据模型类
        public class WorkOrderModel
        {
            [DisplayName("选择")]
            public bool IsSelected { get; set; }
            [DisplayName("编号")]
            public long Id { get; set; }

            [DisplayName("编号")]
            public string Code { get; set; }

            [DisplayName("生产类型")]
            public string ProductionType { get; set; }

            [DisplayName("客户id")]
            public long Client { get; set; }
            /// <summary>
            /// 客户名称
            /// </summary>
            [DisplayName("客户")]
            public string CustomerName { get; set; }


            [DisplayName("产品主数据")]
            public string Masterdata { get; set; }

            [DisplayName("产线id")]
            public long Line { get; set; }
            [DisplayName("产线")]
            public string ProcessName { get; set; } // 工序名称

            [DisplayName("状态")]
            public string State { get; set; }

            [DisplayName("进度")]
            public string Progress { get; set; }

            [DisplayName("生产数量")]
            public int ProductionCount { get; set; }

            [DisplayName("开始时间")]
            public DateTime BeginTime { get; set; }

            [DisplayName("结束时间")]
            public DateTime EndTime { get; set; }

            [DisplayName("是否允许")]
            public string Whether { get; set; }

            [DisplayName("上传文件")]
            public string Img { get; set; }

            [DisplayName("生产描述")]
            public string ProductionDesc { get; set; }

            [DisplayName("输入数量")]
            public int Input { get; set; }

            [DisplayName("良品数量")]
            public int Good { get; set; }

            [DisplayName("报废数量")]
            public int Scrap { get; set; }

            [DisplayName("来源")]
            public string Source { get; set; }

            [DisplayName("生产单号")]
            public string ProductionNumber { get; set; }

            [DisplayName("创建人")]
            public string CreatedBy { get; set; }

            [DisplayName("创建时间")]
            public DateTime CreatedAt { get; set; }

            // 不使用DisplayName特性，避免数据绑定到此属性
            // 这个属性只用于显示按钮
            public string operation { get; set; }
        }
        /// <summary>
        /// 删除工单信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void DelOrder_Click(object sender, EventArgs e)
        {
            var checkedIds = new List<long>();
            for (int rowHandle = 0; rowHandle < gridView1.RowCount; rowHandle++)
            {
                bool isChecked = false;
                var val = gridView1.GetRowCellValue(rowHandle, "IsSelected");
                if (val != null && val is bool)
                    isChecked = (bool)val;
                if (!isChecked) continue;
                var idObj = gridView1.GetRowCellValue(rowHandle, "Id");
                if (idObj == null) continue;
                long id = Convert.ToInt64(idObj);
                checkedIds.Add(id);
            }
            if (checkedIds.Count == 0)
            {
                XtraMessageBox.Show("请先勾选要删除的行！");
                return;
            }
            if (XtraMessageBox.Show($"确认删除选中的 {checkedIds.Count} 条记录？", "批量删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                return;
            using (var client = new HttpClient { BaseAddress = new Uri(_workorderApiBaseUrl) })
            {
                foreach (var id in checkedIds)
                {
                    var resp = await client.PostAsync($"/api/ProduceModel/DeleteWorkorder?id={id}", new StringContent("", Encoding.UTF8, "application/json"));
                    if (!resp.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show($"删除 Id={id} 失败：{resp.ReasonPhrase}");
                        return;
                    }
                }
            }
            await LoadWorkOrder();
            XtraMessageBox.Show("删除完成！");

        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ExportOrder_Click(object sender, EventArgs e)
        {
            try
            {

                using (var client = new HttpClient { BaseAddress = new Uri(_workorderApiBaseUrl) })
                {
                    // 创建保存对话框
                    SaveFileDialog saveDialog = new SaveFileDialog();
                    saveDialog.Filter = "Excel文件(*.xlsx)|*.xlsx|所有文件(*.*)|*.*";
                    saveDialog.FilterIndex = 1;
                    saveDialog.RestoreDirectory = true;
                    saveDialog.FileName = $"工单数据_{DateTime.Now:yyyyMMdd_HHmmss}";

                    if (saveDialog.ShowDialog() == DialogResult.OK)
                    {
                        string filePath = saveDialog.FileName;

                        // 调用API获取导出文件
                        var response = await client.GetAsync("/api/ProduceModel/ExportWorkOrderToExcel");

                        if (response.IsSuccessStatusCode)
                        {
                            // 读取响应内容
                            byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();

                            // 保存文件
                            File.WriteAllBytes(filePath, fileBytes);

                            XtraMessageBox.Show("数据已成功导出！", "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            // 询问是否打开导出的文件
                            if (XtraMessageBox.Show("是否打开导出的文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{filePath}\"");
                            }
                        }
                        else
                        {
                            XtraMessageBox.Show($"导出失败：{response.ReasonPhrase}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"导出过程中发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复鼠标指针
                this.Cursor = Cursors.Default;
            }
        }

        private void UpdateOrder_Click(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前行的数据
                int rowHandle = gridView1.FocusedRowHandle;
                if (rowHandle >= 0)
                {
                    // 获取当前行的WorkOrderModel对象
                    WorkOrderModel model = gridView1.GetRow(rowHandle) as WorkOrderModel;
                    if (model != null)
                    {
                        // 打开修改窗体，并传递选中的工单数据
                        var updateForm = new UpdateOrderForm(model);

                        // 显示窗体并等待结果
                        DialogResult result = updateForm.ShowDialog();

                        // 如果修改成功，刷新数据
                        if (result == DialogResult.OK)
                        {
                            // 刷新数据
                            LoadWorkOrder();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"修改工单出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}